package com.statistics.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * 各单位获奖情况年度统计表
 **/
public class HonorExportUtils {

    public static void exportExcel(HttpServletResponse response, List<Map<String, Object>> data, String fileName) throws Exception {
        // 设置响应头
        AchExportUtils.setResponse(response,fileName);

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet(fileName != null ? fileName : "Sheet1");

            if (data == null || data.isEmpty()) {
                workbook.write(response.getOutputStream());
                return;
            }

            List<String> headers = new ArrayList<>(data.get(0).keySet());
            createHeaderRow(sheet, headers, AchExportUtils.createHeaderStyle(workbook));
            fillDataRows(sheet, data, headers, AchExportUtils.createTotalStyle(workbook));
            autoSizeColumns(sheet, headers.size());
            workbook.write(response.getOutputStream());
        }
    }

    // 生成表头行
    private static void createHeaderRow(Sheet sheet, List<String> headers, CellStyle style) {
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.size()+1; i++) {
            Cell cell = headerRow.createCell(i);
            if ( i == 0 ){
                cell.setCellValue("序号");
            }else{
                cell.setCellValue(headers.get(i-1).equals("unitName")?"部门":headers.get(i-1));
            }
            cell.setCellStyle(style);
        }
    }

    // 填充数据行
    private static void fillDataRows(Sheet sheet, List<Map<String, Object>> data, List<String> headers, CellStyle style) {
        int rowNum = 1;
        for (Map<String, Object> rowData : data) {
            Row row = sheet.createRow(rowNum++);
            for (int i = 0; i < headers.size() + 1; i++) {
                Cell cell = row.createCell(i);
                if ( i == 0 ){
                    AchExportUtils.setCellValue(cell, rowNum-1);
                }else{
                    Object value = rowData.get(headers.get( i - 1 ));
                    AchExportUtils.setCellValue(cell, value);
                }
                cell.setCellStyle(style);
            }
        }
    }

    // 自动调整列宽
    private static void autoSizeColumns(Sheet sheet, int columnCount) {
        for (int i = 0; i < columnCount; i++) {
            sheet.autoSizeColumn(i);
        }
    }
}